﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;

namespace WindowsTest
{
    /// <summary>
    /// 常用功能
    /// </summary>
    class Features
    {
        #region 批量黑白转换

        /// <summary>
        /// 批量将图片进行黑白反色处理
        /// </summary>
        /// <param name="path">要处理图片所在目录</param>
        public static string BatchBrackToWihte(string path)
        {
            string _parentFolderName = @"Temp\" + path.Substring(path.LastIndexOf('\\') + 1) + "\\";
            if (!Directory.Exists("Temp"))
            {
                Directory.CreateDirectory("Temp");
            }
            if (!Directory.Exists(_parentFolderName))
            {
                Directory.CreateDirectory(_parentFolderName);
            }
            else
            {
                FilesClean.Clean(_parentFolderName);
            }
            var dir = new DirectoryInfo(path);
            FileInfo[] finfos = dir.GetFiles();
            if (finfos.Any())
            {
                foreach (var fileInfo in finfos)
                {
                    try
                    {
                        if (isImage(fileInfo.Extension))
                        {
                            var bm = new Bitmap(fileInfo.FullName);
                            var im = Common.ToBinary(bm, Matlab.GetThreshold(bm));
                            im = Matlab.Inverse(im);
                            var obm = Common.ToBitmap(im);
                            obm.Save(_parentFolderName + fileInfo.Name, getImageFormat(fileInfo.Extension));
                            obm.Dispose();
                        }
                    }
                    catch (Exception e)
                    {
                        LogService.Error(e);
                    }
                }
            }

            return _parentFolderName;
        }

        #endregion

        #region 批量格式转换

        /// <summary>
        /// 图像批量格式转换方法
        /// </summary>
        /// <param name="path">指定图像所在的目录</param>
        /// <param name="format">指定要转换的格式</param>
        public static string BatchImageFormat(string path, ImageFormat format)
        {
            string _parentFolderName = @"Temp\" + path.Substring(path.LastIndexOf('\\') + 1) + "\\";
            if (!Directory.Exists("Temp"))
            {
                Directory.CreateDirectory("Temp");
            }
            if (!Directory.Exists(_parentFolderName))
            {
                Directory.CreateDirectory(_parentFolderName);
            }
            else
            {
                FilesClean.Clean(_parentFolderName);
            }
            var dir = new DirectoryInfo(path);
            FileInfo[] finfos = dir.GetFiles();
            if (finfos.Any())
            {
                foreach (var fileInfo in finfos)
                {
                    try
                    {
                        if (isImage(fileInfo.Extension))
                        {
                            var bm = new Bitmap(fileInfo.FullName);
                            bm.Save(_parentFolderName + fileInfo.Name.Replace(fileInfo.Extension, "") + "." + format, format);
                            bm.Dispose();
                        }
                    }
                    catch (Exception e)
                    {
                        LogService.Error(e);
                    }
                }
            }

            return _parentFolderName;
        }

        #endregion

        #region 批量边缘扩张

        /// <summary>
        /// 批量图像边缘扩张方法
        /// </summary>
        /// <param name="path">要处理的图片所在目录</param>
        /// <param name="enWidth">要扩张的宽度</param>
        /// <param name="enHeight">要扩张的高度</param>
        /// <returns>处理后的图片所在目录</returns>
        public static string BatchEageEnlarger(string path, int enWidth, int enHeight)
        {
            string _parentFolderName = @"Temp\" + path.Substring(path.LastIndexOf('\\') + 1) + "\\";
            if (!Directory.Exists("Temp"))
            {
                Directory.CreateDirectory("Temp");
            }
            if (!Directory.Exists(_parentFolderName))
            {
                Directory.CreateDirectory(_parentFolderName);
            }
            else
            {
                FilesClean.Clean(_parentFolderName);
            }
            var dir = new DirectoryInfo(path);
            FileInfo[] finfos = dir.GetFiles();
            if (finfos.Any())
            {
                foreach (var fileInfo in finfos)
                {
                    try
                    {
                        if (isImage(fileInfo.Extension))
                        {
                            var bm = new Bitmap(fileInfo.FullName);
                            bm = Matlab.RectangleEageEnlarge(bm, enWidth, enHeight);
                            bm.Save(_parentFolderName + fileInfo.Name, getImageFormat(fileInfo.Extension));
                            bm.Dispose();
                        }
                    }
                    catch (Exception e)
                    {
                        LogService.Error(e);
                    }
                }
            }

            return _parentFolderName;
        }

        #endregion

        #region 批量二值化

        /// <summary>
        /// 用C++方法批量二值化
        /// </summary>
        /// <param name="path">要二值化的图像所片路径</param>
        /// <param name="t">阈值，默认为3*3*360</param>
        /// <returns>二值化后的图像目录</returns>
        public static string BatchToTwoValue(string path, int t = 3*3*360)
        {
            string _parentFolderName = @"Temp\" + path.Substring(path.LastIndexOf('\\') + 1) + "\\";
            if (!Directory.Exists("Temp"))
            {
                Directory.CreateDirectory("Temp");
            }
            if (!Directory.Exists(_parentFolderName))
            {
                Directory.CreateDirectory(_parentFolderName);
            }
            else
            {
                FilesClean.Clean(_parentFolderName);
            }
            var dir = new DirectoryInfo(path);
            FileInfo[] finfos = dir.GetFiles();
            if (finfos.Any())
            {
                foreach (var fileInfo in finfos)
                {
                    try
                    {
                        if (isImage(fileInfo.Extension))
                        {
                            var bm = new Bitmap(fileInfo.FullName);
                            bm = Matlab.CtoTwoValue(bm, t);
                            bm.Save(_parentFolderName + fileInfo.Name, getImageFormat(fileInfo.Extension));
                            bm.Dispose();
                        }
                    }
                    catch (Exception e)
                    {
                        LogService.Error(e);
                    }
                }
            }
            return _parentFolderName;
        }

        #endregion

        #region 批量OCR

        /// <summary>
        /// 批量图像OCR识别方法
        /// </summary>
        /// <param name="path">要批量处理的文件夹目录</param>
        /// <returns>反回识别结果（记录识别结果的文本文档）</returns>
        public static string BatchOCR(string path)
        {
            string _parentFolderName = @"Temp\" + path.Substring(path.LastIndexOf('\\') + 1) + "\\";
            if (!Directory.Exists("Temp"))
            {
                Directory.CreateDirectory("Temp");
            }
            if (!Directory.Exists(_parentFolderName))
            {
                Directory.CreateDirectory(_parentFolderName);
            }
            else
            {
                FilesClean.Clean(_parentFolderName);
            }
            if (!Directory.Exists(_parentFolderName + "Images"))
            {
                Directory.CreateDirectory(_parentFolderName + "Images");
            }
            var dir = new DirectoryInfo(path);
            FileInfo[] finfos = dir.GetFiles();
            if (finfos.Any())
            {
                foreach (var fileInfo in finfos)
                {
                    try
                    {
                        if (isImage(fileInfo.Extension))
                        {
                            var imageSavePath = fileInfo.FullName;
                            if (!Equals(getImageFormat(fileInfo.Extension), ImageFormat.Tiff))
                            {
                                imageSavePath = _parentFolderName + "Images\\" + fileInfo.Name.Substring(0, fileInfo.Name.LastIndexOf('.')) + ".tif";
                                var bm = new Bitmap(fileInfo.FullName);
                                bm.Save(imageSavePath, ImageFormat.Tiff);
                                bm.Dispose();
                            }

                            string str = "";
                            OCR.ImageToOCR(imageSavePath, ref str);
                            if (!String.IsNullOrEmpty(str))
                            {
                                write(_parentFolderName + "OCRText.txt", str);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        LogService.Error(e);
                    }
                }
            }
            return _parentFolderName + "OCRText.txt";
        }

        #endregion

        #region 批量去噪

        /// <summary>
        /// 批量图像去噪方法
        /// </summary>
        /// <param name="path">要批量处理的文件夹目录</param>
        /// <returns>反回识别结果（记录识别结果的文本文档）</returns>
        public static string BatchDenoising(string path)
        {
            string _parentFolderName = @"Temp\" + path.Substring(path.LastIndexOf('\\') + 1) + "\\";
            if (!Directory.Exists("Temp"))
            {
                Directory.CreateDirectory("Temp");
            }
            if (!Directory.Exists(_parentFolderName))
            {
                Directory.CreateDirectory(_parentFolderName);
            }
            else
            {
                FilesClean.Clean(_parentFolderName);
            }
            var dir = new DirectoryInfo(path);
            FileInfo[] finfos = dir.GetFiles();
            if (finfos.Any())
            {
                foreach (var fileInfo in finfos)
                {
                    try
                    {
                        if (isImage(fileInfo.Extension))
                        {
                            if (!Equals(getImageFormat(fileInfo.Extension), ImageFormat.Jpeg))
                            {
                                string imageSavePath = _parentFolderName + fileInfo.Name.Substring(0, fileInfo.Name.LastIndexOf('.')) + ".jpg";
                                var bm = new Bitmap(fileInfo.FullName);
                                var bs = Common.ToBinary(bm, Matlab.GetThreshold(bm));

                                //正方结构开启
                                bs = Matlab.Erode(bs, bm.Width, bm.Height, 2);
                                bs = Matlab.Dilate(bm, bs, 2);

                                //正方结构闭合
                                bs = Matlab.Dilate(bm, bs, 2);
                                bs = Matlab.Erode(bs, bm.Width, bm.Height, 2);
                                var obm = Common.ToBitmap(bs);

                                obm.Save(imageSavePath, ImageFormat.Jpeg);
                                bm.Dispose();
                                obm.Dispose();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        LogService.Error(e);
                    }
                }
            }
            return _parentFolderName;
        }

        #endregion

        #region 公用方法

        /// <summary>
        /// 判断是否是图片文件
        /// </summary>
        /// <param name="extension">文件后缀，包括“.”</param>
        /// <returns>是否是图片文件</returns>
        private static bool isImage(string extension)
        {
            var ex = extension.Substring(1);//去掉“.”
            if (ex.ToUpper() == "JPG" || ex.ToUpper() == "JPEG" || ex.ToUpper() == "TIF" || ex.ToUpper() == "PNG" || ex.ToUpper() == "BMP" || ex.ToUpper() == "TIFF")
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 获取图像的格式
        /// </summary>
        /// <param name="extension">文件名后缀</param>
        /// <returns>图像格式</returns>
        private static ImageFormat getImageFormat(string extension)
        {
            ImageFormat format = ImageFormat.Tiff;
            switch (extension.Substring(1).ToUpper())
            {
                case "JPEG":
                    format = ImageFormat.Jpeg;
                    break;
                case "BMP":
                    format = ImageFormat.Bmp;
                    break;
                case "GIF":
                    format = ImageFormat.Gif;
                    break;
                case "PNG":
                    format = ImageFormat.Png;
                    break;
                case "WMF":
                    format = ImageFormat.Wmf;
                    break;
            }
            return format;
        }

        /// <summary>
        /// 将信息写入文件
        /// </summary>
        /// <param name="path">文件所在目录</param>
        /// <param name="message">要写入的内容</param>
        private static void write(String path, String message)
        {
            var fi = new FileInfo(path);
            try
            {
                StreamWriter sw = fi.AppendText();
                sw.WriteLine(message);
                sw.Close();
            }
            catch (Exception e)
            {
                LogService.Error(e);
                LogService.Info("文件写入异常");
            }
        }

        #endregion
    }
}
